package com.easyim.imserver.utils;

import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Slf4j
public class NodeInfoUtils {

    //先获取channel中的会话存在哪个node 如果是在当前节点 直接忽略不就完事了 如果在其他节点 那么就建立一个tcp客户端 发送一个转发消息
    //让那个节点去投递  如果没有和节点的连接 那么就创建一个 为了方便查看 其实写入redis 里面的 应该是ip:port格式
    //但是每个通道中存的 应该是一个格式 解析会就可以得到的 这样子方便了获取channel

    private static final  String localIp = getLocalIp();

    private static final Integer currentNode = getNodeIdByIp();

    private static String getIpByNodeId(Integer nodeIpInt) {
        StringBuilder ipAddress = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int part = (nodeIpInt >> (24 - i * 8)) & 0xFF;
            ipAddress.append(part);
            if (i < 3) {
                ipAddress.append(".");
            }
        }
        return ipAddress.toString();
    }

    public static Integer getLocalNodeId() {
        return currentNode;
    }

    public static String getLocalNodeIp() {
        return localIp;
    }

    private static int getNodeIdByIp() {
        String[] ipParts = localIp.split("\\.");
        int ipInt = 0;
        if (ipParts.length == 4) {
            for (int i = 0; i < 4; i++) {
                int part = Integer.parseInt(ipParts[i]);
                ipInt = (ipInt << 8) + part;
            }
        } else {
            throw new IllegalArgumentException("Invalid IP address format");
        }
        log.info("current node  convert ip :{} to node:{}", localIp, ipInt);
        return ipInt;
    }

    private static String getLocalIp() {
        InetAddress localHost = null;
        try {
            localHost = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
        String ipAddress = localHost.getHostAddress();
        return ipAddress;
    }
}
